package com.shine.minepressure.ui.webview;


import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.DownloadListener;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import androidx.core.content.FileProvider;

import com.shine.minepressure.BR;
import com.shine.minepressure.R;
import com.shine.minepressure.app.Constants;
import com.shine.minepressure.base.BaseActivity;
import com.shine.minepressure.bus.RxBus;
import com.shine.minepressure.bus.RxSubscriptions;
import com.shine.minepressure.databinding.ActivityCommonWebViewBinding;
import com.shine.minepressure.download.DownloadInfo;
import com.shine.minepressure.utils.CommonUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

public class CommonWebViewActivity extends BaseActivity<ActivityCommonWebViewBinding, CommonWebViewModel> {
    private String mUrl = "";
    private String titleFrom = "";
    private boolean canBack = false;

    private Disposable downloadDisposable;
    private List<String> downloadUrlList;
    private boolean startInstall;
    private List<String> apkUrl = new ArrayList<>();
    private String h5DownloadUrl;
    private int percent;

    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.activity_common_web_view;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    public CommonWebViewModel initViewModel() {
        return new CommonWebViewModel(this);
    }

    public static void start(Context context, String url, String title, int productId, int subjectId) {
        Intent intent = new Intent(context, CommonWebViewActivity.class);
        intent.putExtra(Constants.BUNDLE_EXTRA, url);
        intent.putExtra("title", title);
        intent.putExtra("productId", productId);
        intent.putExtra("subjectId", subjectId);
        context.startActivity(intent);
    }

    public static void start(Context context, String url, int id) {
        Intent intent = new Intent(context, CommonWebViewActivity.class);
        intent.putExtra(Constants.BUNDLE_EXTRA, url);
        intent.putExtra("id", id);
        context.startActivity(intent);
    }

    public static void start(Context context, String url, String title, int id) {
        Intent intent = new Intent(context, CommonWebViewActivity.class);
        intent.putExtra(Constants.BUNDLE_EXTRA, url);
        intent.putExtra("id", id);
        intent.putExtra("title", title);
        context.startActivity(intent);
    }

    @Override
    public void initData() {
        super.initData();
        overrideBack(false);

        mUrl = getIntent().getStringExtra(Constants.BUNDLE_EXTRA);


        int id = getIntent().getIntExtra("id", 0);
        initTitle(this, getIntent().getStringExtra("title"));

        if (id == 100) {
            initTitle(this, getIntent().getStringExtra("title"));
            binding.walkAroundLayout.setVisibility(View.GONE);
            overrideBack(true);
        }


        initWebView();
        binding.sobotMWebView.loadUrl(mUrl);

        binding.walkAroundLayout.setOnClickListener(this);

        //下载完成安装apk
        downloadDisposable = RxBus.getDefault().toObservable(DownloadInfo.class)
                .subscribe(new Consumer<DownloadInfo>() {
                    @Override
                    public void accept(DownloadInfo info) throws Exception {
                        if (DownloadInfo.DOWNLOAD_OVER.equals(info.getDownloadStatus())) {
                            if (!TextUtils.isEmpty(h5DownloadUrl) && h5DownloadUrl.equals(info.getUrl())) {
                                String appDownLoadPath = CommonUtils.FILE_PATH + info.getFileName();
                                installApk(new File(appDownLoadPath));
                            }
                            if (downloadUrlList != null && downloadUrlList.contains(info.getUrl())) {
                                startInstall = true;
                                String appDownLoadPath = CommonUtils.FILE_PATH + info.getFileName();
                                apkUrl.add(appDownLoadPath);
                                installApk(new File(appDownLoadPath));
                            }
                        }
                    }
                });
        RxSubscriptions.add(downloadDisposable);
    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.walkAroundLayout) {
        }
    }

    @Override
    public void initBack() {
        if (canBack)
            finishActivityForResult();
        else
            finish();
    }

    @SuppressLint("NewApi")
    private void initWebView() {
        if (Build.VERSION.SDK_INT >= 11) {
            try {
                binding.sobotMWebView.removeJavascriptInterface("searchBoxJavaBridge_");
            } catch (Exception e) {
                //ignor
            }
        }
        binding.sobotMWebView.setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
                if (getIntent().getIntExtra("id", 0) == 100)
                    return;
                h5DownloadUrl = url;
                //检测到下载文件就打开系统浏览器
//                Intent intent = new Intent();
//                intent.setAction("android.intent.action.VIEW");
//                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                Uri content = Uri.parse(url);
//                intent.setData(content);
//                startActivity(intent);


            }
        });
        binding.sobotMWebView.removeJavascriptInterface("searchBoxJavaBridge_");
        binding.sobotMWebView.getSettings().setDefaultFontSize(16);
        binding.sobotMWebView.getSettings().setTextZoom(100);
        binding.sobotMWebView.getSettings().setJavaScriptEnabled(true);
        binding.sobotMWebView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
        // 设置可以使用localStorage
        binding.sobotMWebView.getSettings().setDomStorageEnabled(true);
        binding.sobotMWebView.getSettings().setLoadsImagesAutomatically(true);
        binding.sobotMWebView.getSettings().setBlockNetworkImage(false);
        binding.sobotMWebView.getSettings().setSavePassword(false);
        binding.sobotMWebView.getSettings().setUserAgentString(binding.sobotMWebView.getSettings().getUserAgentString() + " sobot");

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            binding.sobotMWebView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }

        // 应用可以有数据库
        binding.sobotMWebView.getSettings().setDatabaseEnabled(true);

        // 应用可以有缓存
        binding.sobotMWebView.getSettings().setAppCacheEnabled(true);
        binding.sobotMWebView.setWebViewClient(new WebViewClient() {

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                //注释的地方是打开其它应用，比如qq
                /*if (url.startsWith("http") || url.startsWith("https")) {
                    return false;
                } else {
                    Intent in = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                    startActivity(in);
                    return true;
                }*/
                return false;
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);

            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
//                sobot_webview_goback.setEnabled(binding.sobotMWebView.canGoBack());
//                sobot_webview_forward.setEnabled(binding.sobotMWebView.canGoForward());
                if (!mUrl.replace("http://", "").replace("https://", "").equals(view.getTitle())) {
                    setTitle(view.getTitle());
                } else {
                    setTitle(titleFrom);
                }
            }
        });

        binding.sobotMWebView.setWebChromeClient(new WebChromeClient() {

            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                if (!mUrl.replace("http://", "").replace("https://", "").equals(title)) {
                    setTitle(title);
                } else {
                    setTitle(titleFrom);
                }
            }

            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (newProgress > 0 && newProgress < 100) {
                    binding.sobotLoadProgress.setVisibility(View.VISIBLE);
                    binding.sobotLoadProgress.setProgress(newProgress);
                } else if (newProgress == 100) {
                    binding.sobotLoadProgress.setVisibility(View.GONE);
                }
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        if (binding.sobotMWebView != null) {
            binding.sobotMWebView.onResume();
        }
    }

    @Override
    public void onPause() {
        if (binding.sobotMWebView != null) {
            binding.sobotMWebView.onPause();
        }
        super.onPause();
    }

    @Override
    public void onDestroy() {
        RxSubscriptions.remove(downloadDisposable);

        if (binding.sobotMWebView != null) {
            binding.sobotMWebView.removeAllViews();
            final ViewGroup viewGroup = (ViewGroup) binding.sobotMWebView.getParent();
            if (viewGroup != null) {
                viewGroup.removeView(binding.sobotMWebView);
            }
            binding.sobotMWebView.destroy();
        }
        super.onDestroy();
    }

//    @Override
//    public void onBackPressed() {
//        if (binding.sobotMWebView != null && binding.sobotMWebView.canGoBack()) {
//            binding.sobotMWebView.goBack();
//        } else {
//            super.onBackPressed();
//            finish();
//        }
//    }

    protected void onSaveInstanceState(Bundle outState) {
        //被摧毁前缓存一些数据
        outState.putString("url", mUrl);
        super.onSaveInstanceState(outState);
    }


    private void copyUrl(String url) {
        if (TextUtils.isEmpty(url)) {
            return;
        }

        if (Build.VERSION.SDK_INT >= 11) {
//            LogUtils.i("API是大于11");
            android.content.ClipboardManager cmb = (android.content.ClipboardManager) getApplicationContext().getSystemService(Context.CLIPBOARD_SERVICE);
            cmb.setText(url);
            cmb.getText();
        } else {
//            LogUtils.i("API是小于11");
            android.text.ClipboardManager cmb = (android.text.ClipboardManager) getApplicationContext().getSystemService(Context.CLIPBOARD_SERVICE);
            cmb.setText(url);
            cmb.getText();
        }
    }

    /**
     * 安装下载完成的apk
     *
     * @param file
     */
    private void installApk(File file) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(getUriFromFile(file), "application/vnd.android.package-archive");
        //解决startActivity采取的上下文的Context而不是Activity
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        //解决手机安装软件的权限问题
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        startActivity(intent);
    }

    /**
     * 兼容Android版本获取Uri
     *
     * @param file
     * @return
     */
    private Uri getUriFromFile(File file) {
        Uri fileUri = null;
        if (Build.VERSION.SDK_INT >= 24) { // Android 7.0 以上
            fileUri = FileProvider.getUriForFile(this, "com.tz.quyongnew.fileprovider", file);
        } else {
            fileUri = Uri.fromFile(file);
        }
        return fileUri;
    }

    @Override
    protected void onStop() {
        super.onStop();
        System.out.println("onStop");
        //跳转到apk安装界面,开始安装第一个apk,删除第一个已经打开安装界面的文件路径
        if (startInstall && !apkUrl.isEmpty()) {
            apkUrl.remove(0);
        } else {
            startInstall = false;
            apkUrl.clear();
        }
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        System.out.println("onRestart");
        //无论是否安装返回app，打开下一个apk安装界面
        if (startInstall && !apkUrl.isEmpty()) {
            installApk(new File(apkUrl.get(0)));
        } else {
            startInstall = false;
            apkUrl.clear();
        }
    }
}
